package com.uinnova.product.eam.init;

import com.uinnova.product.eam.config.CacheKeyPrefix;
import com.uino.api.client.permission.IOauthApiSvc;
import com.uino.bean.permission.base.OauthTokenDetail;
import com.uino.util.cache.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description
 *
 * @author lichong
 * @since 2022/5/13 10:18
 */
@Component
public class UserOnlineInterceptor implements HandlerInterceptor {

    @Autowired
    ICacheService cacheService;

    @Autowired
    private IOauthApiSvc oauthApiSvc;

    @Value("${uino.token.online.time:30}")
    private Integer sessionOnlineTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object attribute = request.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE);
        String tokenStr;
        if (attribute instanceof String) {
            tokenStr = (String) attribute;
        } else {
            return true;
        }
        OauthTokenDetail tokenDeatil = oauthApiSvc.getTokenDetailByCode(tokenStr);
        cacheService.setCache(CacheKeyPrefix.UINO_USER_ONLINE_PREFIX + ":" + tokenDeatil.getUserName(), "", sessionOnlineTime * 60 * 1000);
        return true;
    }
}
